package com.flyme.module.base.provider.service.impl;

import com.flyme.common.core.exception.OpenMessageException;
import com.flyme.core.base.supper.service.impl.BaseServiceImpl;
import com.flyme.module.base.client.constants.BaseConstants;
import com.flyme.module.base.client.entity.SystemApi;
import com.flyme.module.base.provider.mapper.SysApiMapper;
import com.flyme.module.base.provider.service.SysApiService;
import com.flyme.module.base.provider.service.SysAuthorizeService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author zyf
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class SysApiServiceImpl extends BaseServiceImpl<SysApiMapper, SystemApi> implements SysApiService {

    @Autowired
    private SysAuthorizeService accessService;

    @Override
    public Boolean isExist(String apiCode) {
        int count = count(q().eq("apiCode",apiCode));
        return count > 0;
    }

    /**
     * 添加接口
     *
     * @param api
     * @return
     */
    @Override
    public Boolean addApi(SystemApi api) {
        if (isExist(api.getApiCode())) {
            throw new OpenMessageException(String.format("%sApi编码已存在,不允许重复添加", api.getApiCode()));
        }
        if (api.getPriority() == null) {
            api.setPriority(new BigDecimal("0"));
        }
        if (api.getStatus() == null) {
            api.setStatus(BaseConstants.ENABLED);
        }
        if (api.getApiCategory() == null) {
            api.setApiCategory(BaseConstants.DEFAULT_API_CATEGORY);
        }
        if(api.getIsPersist()==null){
            api.setIsPersist(BaseConstants.DISABLED);
        }
        api.setCreateTime(new Date());
        api.setUpdateTime(api.getCreateTime());
        return save(api);
    }

    /**
     * 修改接口
     *
     * @param api
     * @return
     */
    @Override
    public Boolean updateApi(SystemApi api) {
        if (api.getId() == null) {
            throw new OpenMessageException("ID不能为空");
        }
        SystemApi savedApi = getById(api.getId());
        if (savedApi == null) {
            throw new OpenMessageException(String.format("%sApi不存在", api.getId()));
        }
        if (!savedApi.getApiCode().equals(api.getApiCode())) {
            // 和原来不一致重新检查唯一性
            if (isExist(api.getApiCode())) {
                throw new OpenMessageException(String.format("%sApi编码已存在,不允许重复添加", api.getApiCode()));
            }
        }
        if (api.getPriority() == null) {
            api.setPriority(new BigDecimal("0"));
        }
        if (api.getApiCategory() == null) {
            api.setApiCategory(BaseConstants.DEFAULT_API_CATEGORY);
        }
        api.setUpdateTime(new Date());
        Boolean count = saveOrUpdate(api);
        // 同步授权表里的信息
        accessService.updateGrantAccess(BaseConstants.RESOURCE_TYPE_API, api.getId());
        return count;
    }

    /**
     * 查询接口
     *
     * @param apiCode
     * @param serviceId
     * @return
     */
    @Override
    public SystemApi getApi(String apiCode, String serviceId) {

        return getOne(q().eq("apiCode",apiCode).eq("serviceId",serviceId));
    }

    /**
     * 更新启用禁用
     *
     * @param apiId
     * @param status
     * @return
     */
    @Override
    public Boolean updateStatus(Long apiId, Integer status) {
        SystemApi api = new SystemApi();
        api.setId(apiId);
        api.setStatus(status);
        api.setUpdateTime(new Date());
        Boolean count = saveOrUpdate(api);
        // 同步授权表里的信息
        accessService.updateGrantAccess(BaseConstants.RESOURCE_TYPE_API, api.getId());
        return count;
    }

    /**
     * 移除接口
     *
     * @param apiId
     * @return
     */
    @Override
    public Boolean removeApi(Long apiId) {
        SystemApi api = getById(apiId);
        if(api!=null && api.getIsPersist().equals(BaseConstants.ENABLED)){
            throw new OpenMessageException(String.format("保留数据,不允许删除"));
        }
        if (accessService.isExist(apiId, BaseConstants.RESOURCE_TYPE_API)) {
            throw new OpenMessageException(String.format("资源已被授权,不允许删除,请取消授权后,再次尝试!"));
        }
        return  removeById(apiId);
    }

    /**
     * 根据编码查询ID
     *
     * @param codes
     * @return
     */
    @Override
    public List<Long> findIdsByCodes(String... codes) {
        List codeList = Lists.newArrayList(codes);
        List<Long> ids = Lists.newArrayList();
        if (codeList.contains("all")) {
            ids.add(1L);
            return ids;
        }
        List<SystemApi> list = list(q().in("apiCode",codeList));
        if (list != null && !list.isEmpty()) {
            list.forEach(item -> {
                ids.add(item.getId());
            });
        }
        return ids;
    }


}
